package com.haiheng.voiceandbook

import android.app.DownloadManager
import android.app.PendingIntent
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.text.TextUtils
import android.util.Log
import com.haiheng.voiceandbook.Constants.Companion.BOOK_PATH
import com.haiheng.voiceandbook.Constants.Companion.DEVICEID
import com.haiheng.voiceandbook.helper.DemoHelper
import com.haiheng.voiceandbook.receiver.DownloadCompleteReceiver
import com.haiheng.voiceandbook.receiver.MyPlayerReceiver
import com.haiheng.voiceandbook.service.RestartService
import com.haiheng.voiceandbook.utils.AppUtils
import com.haiheng.voiceandbook.utils.SpUtil
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.bugly.crashreport.CrashReport.UserStrategy
import com.ximalaya.ting.android.opensdk.datatrasfer.CommonRequest
import com.ximalaya.ting.android.opensdk.datatrasfer.DeviceInfoProviderDefault
import com.ximalaya.ting.android.opensdk.player.appnotification.XmNotificationCreater
import com.ximalaya.ting.android.opensdk.util.BaseUtil
import com.ximalaya.ting.android.opensdk.util.SharedPreferencesUtil
import org.geometerplus.android.fbreader.FBReaderApplication
import java.io.File
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit


class MyApplication : FBReaderApplication(), DemoHelper.AppIdsUpdater {

    val TAG = "MyApplication"
    val appKey = "4b6e53a608b1dccf072882cd973714d2"
    val packId = "com.haiheng.voiceandbook"
    val appSecret = "90ab279f0d38e8ac06bec62d3f61418f"

    /**
     * 线程池
     */
    lateinit var executor: ThreadPoolExecutor
    override fun onCreate() {
        super.onCreate()
        instance = this
        initFileDir()
        initThreadPool()
        initXiMaLaya()
        val customExceptionHandler = CustomExceptionHandler(this)
        Thread.setDefaultUncaughtExceptionHandler(customExceptionHandler)

        initBugly()
        registerActivityLifecycleCallbacks(AppForegroundListener())
        try {
            // 启动后台服务
            val serviceIntent = Intent(this, RestartService::class.java)
            // 使用 startForegroundService 方法启动服务
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(serviceIntent)
            } else {
                startService(serviceIntent)
            }
        }catch (ex:Exception){
         Log.e("ddd","服务启动异常处理")
        }
    }



    private fun initBugly() {
        var deviceId = SpUtil.getString(instance, DEVICEID)
        if (TextUtils.isEmpty(deviceId)){
            val random = ((Math.random() * 9 + 1) * 100000).toInt().toString()
            SpUtil.putString(instance, DEVICEID,random)
        }


        val strategy = UserStrategy(instance)
        strategy.setAppChannel(Constants.getLibraryCode())
//        strategy.setAppVersion(BuildConfig.VERSION_NAME)
        strategy.setDeviceID(AppUtils.getDeviceId())
        changeBuglyUserDate()
        //...在这里设置strategy的属性，在bugly初始化时传入
        CrashReport.initCrashReport(getApplicationContext(), "080f57c011", false,strategy);

    }


    fun changeBuglyUserDate() {
        CrashReport.putUserData(instance, "LibraryCode",Constants.getLibraryCode())
        CrashReport.putUserData(instance, "AppId",Constants.getAppId())
        CrashReport.putUserData(instance, "DeviceId",AppUtils.getDeviceId())
        CrashReport.putUserData(instance, "macDeviceId",Constants.getDevicesId())
    }
    /**
     * 初始化喜马拉雅
     */
    private fun initXiMaLaya() {
        if (BaseUtil.isMainProcess(this)){
            oaid = SharedPreferencesUtil.getInstance(
                applicationContext
            ).getString(KEY_LAST_OAID)
            DemoHelper(this).getDeviceIds(applicationContext)
            val mXimalaya = CommonRequest.getInstanse()
            mXimalaya.setAppkey(appKey)
            mXimalaya.setPackid(packId)
            mXimalaya.init(this, appSecret, object : DeviceInfoProviderDefault(applicationContext) {
                override fun oaid(): String {

//                    Log.e("dddd","init:"+oaid)
                    // 合作方要尽量优先回传用户真实的oaid，使用oaid可以关联并打通喜马拉雅主app中记录的用户画像数据，对后续个性化推荐接口推荐给用户内容的准确性会有极大的提升！
                    return oaid!!
                }
            })

            CommonRequest.getInstanse().setUseHttps(true)

            val instanse = XmNotificationCreater.getInstanse(this)
            instanse.setNextPendingIntent(null as PendingIntent?)
            instanse.setPrePendingIntent(null as PendingIntent?)
            val actionName = "com.app.test.android.Action_Close"
            val intent = Intent(actionName)
            intent.setClass(this, MyPlayerReceiver::class.java)
            val broadcast = PendingIntent.getBroadcast(this, 0, intent, 0)
            instanse.setClosePendingIntent(broadcast)
            val pauseActionName = "com.app.test.android.Action_PAUSE_START"
            val intent1 = Intent(pauseActionName)
            intent1.setClass(this, MyPlayerReceiver::class.java)
            val broadcast1 = PendingIntent.getBroadcast(this, 0, intent1, 0)
            instanse.setStartOrPausePendingIntent(broadcast1)
        }
    }

    /**
     *  初始化线程池
     */
    private fun initThreadPool() {
        /**
         * 阻塞队列
         */
        var queue = LinkedBlockingQueue<Runnable>()
        /**
         * 线程池
         */
        executor = ThreadPoolExecutor(2, 2, 30, TimeUnit.MINUTES, queue)
    }

    /**
     * 初始化下载的文件夹
     */
    private fun initFileDir() {
        val fileDr = File(BOOK_PATH)
        if (!fileDr.exists()) {
            fileDr.mkdir()
        }
    }

    //伴生对象
    companion object {
        private lateinit var instance: MyApplication
        fun getInstance(): MyApplication {
            return instance
        }
    }

    private val KEY_LAST_OAID = "last_oaid"
    private var oaid: String? = null
    override fun OnOaidAvalid(ids: String) {
        oaid = ids
        SharedPreferencesUtil.getInstance(applicationContext)
            .saveString(KEY_LAST_OAID, ids)

        Log.e(TAG, "OnOaidAvalid:  $ids")
    }

}